#include "showsurvey.h"
#include "ui_showsurvey.h"
#include "database.h"
#include <QScrollArea>
#include <QWidget>
#include <QVBoxLayout>

Showsurvey::Showsurvey(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Showsurvey)
{
    ui->setupUi(this);
    this->setWindowTitle("问卷收集");
    db = Database::getInstance().getDatabase();
}

Showsurvey::~Showsurvey()
{
    delete ui;
}

void Showsurvey::on_pushButton_clicked()
{
    QSqlQuery query(db);
    if (query.exec("SELECT DISTINCT client_name FROM submissions"))
    {
        // 清空现有的行
        int rowCount = ui->tableWidget->rowCount();
        for (int i = rowCount - 1; i >= 0; --i) {
            ui->tableWidget->removeRow(i);
        }

        int row = 0;
        while (query.next())
        {
            QString clientName = query.value(0).toString();

            // 获取该用户的第一个提交记录
            QSqlQuery subQuery(db);
            if (subQuery.exec(QString("SELECT id, submit_time FROM submissions WHERE client_name = '%1' LIMIT 1").arg(clientName)) && subQuery.next())
            {
                int userId = subQuery.value(0).toInt();
                QString submitTime = subQuery.value(1).toString();
                ui->tableWidget->insertRow(row);
                ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(userId)));
                ui->tableWidget->setItem(row, 1, new QTableWidgetItem(clientName));
                ui->tableWidget->setItem(row, 2, new QTableWidgetItem(submitTime));

                QPushButton *viewButton = new QPushButton("查看", this);
                ui->tableWidget->setCellWidget(row, 3, viewButton);
                connect(viewButton, &QPushButton::clicked, [this, clientName]()
                { showSubmitDetail(clientName); });

                row++;
            }
        }
    }
    else
    {
        qDebug() << "Database error:" << query.lastError().text();
    }
}

void Showsurvey::showSubmitDetail(const QString &clientName)
{
    QSqlQuery query(db);
    if (query.exec(QString("SELECT id, submit_time FROM submissions WHERE client_name = '%1'").arg(clientName)))
    {
        clientSubmissions.clear();
        while (query.next())
        {
            int submissionId = query.value(0).toInt();
            QString submitTime = query.value(1).toString();

            clientSubmissions[clientName].append(submissionId);
        }

        if (!clientSubmissions.contains(clientName) || clientSubmissions[clientName].isEmpty())
        {
            qDebug() << "No submissions found for client:" << clientName;
            return;
        }

        QDialog *dialog = new QDialog(this);
        dialog->setWindowTitle("Submission Details");

        // 设置对话框的初始大小
        dialog->resize(800, 600);

        QVBoxLayout *dialogLayout = new QVBoxLayout(dialog);

        QFormLayout *formLayout = new QFormLayout();
        formLayout->addRow("用户名:", new QLabel(clientName));

        // 获取第一个提交的时间作为表单的提交时间
        QString firstSubmitTime;
        if (!clientSubmissions[clientName].isEmpty())
        {
            int firstSubmissionId = clientSubmissions[clientName].first();
            QSqlQuery timeQuery(db);
            if (timeQuery.exec(QString("SELECT submit_time FROM submissions WHERE id = %1").arg(firstSubmissionId)) && timeQuery.next())
            {
                firstSubmitTime = timeQuery.value(0).toString();
            }
        }

        formLayout->addRow("提交时间:", new QLabel(firstSubmitTime));

        dialogLayout->addLayout(formLayout);

        // 创建一个滚动区域
        QScrollArea *scrollArea = new QScrollArea(dialog);
        scrollArea->setWidgetResizable(true);

        // 创建一个用于放置内容的QWidget
        QWidget *contentWidget = new QWidget();
        QVBoxLayout *contentLayout = new QVBoxLayout(contentWidget);

        for (int submissionId : clientSubmissions[clientName])
        {
            QSqlQuery answersQuery(db);
            if (answersQuery.exec(QString("SELECT question_id, answer FROM submissions WHERE id = %1").arg(submissionId)))
            {
                while (answersQuery.next())
                {
                    int questionId = answersQuery.value(0).toInt();
                    QString answer = answersQuery.value(1).toString();

                    QSqlQuery questionQuery(db);
                    if (questionQuery.exec(QString("SELECT text, options FROM questions WHERE id = %1").arg(questionId)))
                    {
                        if (questionQuery.next())
                        {
                            QString questionText = questionQuery.value(0).toString();
                            QString optionsStr = questionQuery.value(1).toString();

                            QGroupBox *groupBox = new QGroupBox(questionText);
                            QVBoxLayout *groupBoxLayout = new QVBoxLayout(groupBox);

                            QStringList optionsList = optionsStr.split('|');
                            QButtonGroup *buttonGroup = new QButtonGroup(this);
                            buttonGroup->setExclusive(true);

                            for (const QString &option : optionsList)
                            {
                                QRadioButton *radioButton = new QRadioButton(option);
                                groupBoxLayout->addWidget(radioButton);
                                buttonGroup->addButton(radioButton);

                                if (option == answer)
                                {
                                    radioButton->setChecked(true);
                                    radioButton->setEnabled(false);
                                }
                                else
                                {
                                    radioButton->setEnabled(false);
                                }
                            }

                            contentLayout->addWidget(groupBox);
                        }
                        else
                        {
                            qDebug() << "Question not found for ID:" << questionId;
                        }
                    }
                    else
                    {
                        qDebug() << "Database error:" << questionQuery.lastError().text();
                    }
                }
            }
            else
            {
                qDebug() << "Database error:" << answersQuery.lastError().text();
            }
        }

        // 将内容Widget添加到滚动区域
        scrollArea->setWidget(contentWidget);
        dialogLayout->addWidget(scrollArea);

        QPushButton *closeButton = new QPushButton("Close");
        dialogLayout->addWidget(closeButton);
        connect(closeButton, &QPushButton::clicked, dialog, &QDialog::accept);

        dialog->exec();
    }
    else
    {
        qDebug() << "Database error:" << query.lastError().text();
    }
}

void Showsurvey::on_pushButton_exit_clicked()
{
    emit show_main();
}
